<?php
/**
 * Created by PhpStorm.
 * User: zhengzifan
 * Date: 2017/3/16
 * Time: 11:05
 */

namespace app\admin\controller;
use think\Loader;

class SuppliersController extends CommonController{

    public $model;
    public $businesses_id;
    
    public $SupplierColumnNameArr = [
        '名称' => 'name',
        '简称' => 'nickname',
        '联系人' => 'contactor_name',
        '联系电话' => 'tel',
        '传真号码' => 'fax',
        '联系地址' => 'address', 
        '主营车型' => 'sale_car_mode',
        '业务范围' => 'scope_remark',
        '行业' => 'industries_id',
        '开户行' => 'bank_id',
        '户名' => 'bank_real_name',
        '账号' => 'bank_account',
        '营业执照' => 'cert_url',
        '法人身份证' => 'card_url',
        '银行卡' => 'bank_url',
        '驾驶证' => 'driver_url'
    ];

    /**
     * 初始化adminModel
     */
    public function _initialize(){
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = model('Suppliers');
        $this->businesses_id = 0;
        if(!empty(session('admin')['businesses_id']) && session('admin')['businesses_id'] > 0){
            $this->businesses_id = session('admin')['businesses_id'];
        }
        $businesses = db('businesses')->select();
        $this->assign([
            'businesses_id' => $this->businesses_id,
            'businesses' => $businesses
        ]);
    }

    /**
     * 列表页
     */
    public function index(){
        $keyword = input('param.keyword');
        $where['id']=['>',0];
        if($keyword){
            $where['name|cotactor_name|tel|mobile'] = ['like','%'.$keyword.'%'];
        }
        if($this->businesses_id > 0){
            $where['businesses_id'] = $this->businesses_id;
        }
        $list = $this->model->where($where)->paginate(20,false,['query' => request()->param()]);
		$page = $list->render();
        $this->assign([
            'list'=>$list,
            'page'=>$page,
            'keyword'=>$keyword
        ]);
        return $this->fetch('index');
    }

    /**
     * 新增与修改
     */
    public function info(){
        $post_id = input('param.id');
        $get_id = input('param.id');
        $info = $this->model->where(['id'=>$get_id])->find();
        if(IS_POST){
            $data = input('param.');
            if($post_id && $post_id>0){
                $data['create_time'] = strtotime($info['create_time']);
                if($this->model->isUpdate(true)->save($data)){
                    admin_log("编辑供应商信息，ID：$post_id");
				    $this->redirect(url('Suppliers/index'));
                }else{
                    $this->error($this->model->getError());
                }
            }else{
                //新增操作
			    $data['creator_id'] = session('admin')['id'];
			    $data['create_time'] = time();
                if($this->model->save($data)){
                    admin_log("新增供应商信息，ID：".$this->model->id);
				    $this->redirect(url('Suppliers/index'));
                }else{
                    $this->error($this->model->getError());
                }
            }
        }
        $banks = db('CommonEnum')->where(['mode_name'=>'银行'])->select();
        $industries = db('CommonEnum')->where(['mode_name'=>'行业'])->select();
        $this->assign([
            'industries' => $industries,
            'banks' => $banks,
            'info' => $info
        ]);
        return $this->fetch('info');
    }

    /**
     * 删除
     */
    public function del(){
        $get_id = input('param.id');
        $info = $this->model->where(['id'=>$get_id])->find();
        if($this->model->where(['id'=>$get_id])->delete()){
            admin_log("删除供应商信息，ID：$get_id");
            $this->redirect(url('Suppliers/index'));
        }else{
            getAlert('操作失败！');
        }
    }
    
    /*
     * 导入Excel
    */
    public function import_data(){
        $json = [
            'status' => 0,
            'msg' => '请选择导入数据文件'
        ];
        $file_urls = input('file_url');
        if(!empty($file_urls) && count($file_urls)>0){
            Loader::import('PHPExcel.PHPExcel');
            Loader::import('PHPExcel.PHPExcel.PHPExcel_IOFactory');
            Loader::import('PHPExcel.PHPExcel.PHPExcel_Cell');
            //实例化PHPExcel
            $objPHPExcel = new \PHPExcel();
            foreach($file_urls as $path){
                $path = ROOT_PATH.$path;
                $re = actionRead($path, 'utf-8');
                $imgs = extractImageFromWorksheet($path);
                array_splice($re, 1, 0);
                $columnNameArr = [];
                if(empty($re) || count($re)<=0){
                    $json['msg'] = '文件不存在任何数据';
                    echo json_encode($json);
                    exit;
                }
                foreach($re[0] as $item){
                    if(!empty($item) && $item !== ''){
                        $columnNameArr[] = $item;    
                    }
                }
                if(empty($columnNameArr) || count($columnNameArr)<=0){
                    $json['msg'] = '文件不存在任何数据';
                    echo json_encode($json);
                    exit;
                }

                /*将数组的键改为自定义名称*/
                $list = [];
                unset($re[0]);
                $ind = 2;
                $ccModel = model('CommonEnum');
                $banks = $ccModel->where(['mode_name'=>'银行'])->select();
                $industries = $ccModel->where(['mode_name'=>'行业'])->select();
                foreach($re as $row){
                    $item = [];
                    for($i = 0;$i < count($columnNameArr);$i++){
                        $key = $columnNameArr[$i];
                        $value = $this->SupplierColumnNameArr[$key];
                        $item_id = 0;
                        if($value == 'industries_id'){
                            $enum_item = searchArray($industries,'name',$row[$i]);
                            if($enum_item['id']>0){
                                $item[$value] = $enum_item['id'];
                            }else{
                                $industrie = [
                                    'mode_name' => '行业',
                                    'enum_name' =>$row[$i],
                                    'sort_id' =>0,
                                    'tag' =>$row[$i],
                                    'score' =>0,
                                    'remark' =>$row[$i],
                                    'creator_id' =>session('admin')['id'],
                                    'create_time' =>time()
                                ];
                                if($item[$value] = $ccModel->insert($industrie,true,true)){
                                    $industries = $ccModel->where(['mode_name'=>'行业'])->select();
                                }
                            }
                            continue;
                        }
                        if($value == 'bank_id'){
                            $enum_item = searchArray($banks,'name',$row[$i]);
                            if($enum_item['id']>0){
                                $item[$value] = $enum_item['id'];
                            }else{
                                $bank = [
                                    'mode_name' => '银行',
                                    'enum_name' =>$row[$i],
                                    'sort_id' =>0,
                                    'tag' =>$row[$i],
                                    'score' =>0,
                                    'remark' =>$row[$i],
                                    'creator_id' =>session('admin')['id'],
                                    'create_time' =>time()
                                ];
                                if($item[$value] = $ccModel->insert($bank,true,true)){
                                    $banks = $ccModel->where(['mode_name'=>'银行'])->select();
                                }
                            }
                            continue;
                        }
                        $item[$value] = $row[$i];
                    }
                    if(!empty($imgs) && count($imgs)>0){
                        foreach($imgs as $key=>$val){
                            if($key == 'M,'.$ind){
                                $item['cert_url'] = $imgs['M,'.$ind];
                            }
                            if($key == 'N,'.$ind){
                                $item['card_url'] = $imgs['N,'.$ind];
                            }
                            if($key == 'O,'.$ind){
                                $item['bank_url'] = $imgs['O,'.$ind];
                            }
                            if($key == 'P,'.$ind){
                                $item['driver_url']= $imgs['P,'.$ind];
                            }
                        }
                    }
                    $item['creator_id'] = session('admin')['id'];
                    $item['create_time'] = time();
                    $list[] = $item;
                    $ind++;
                }
                if(empty($list) || count($list)<=0){
                    $json['msg'] = '文件不存在任何数据';
                    echo json_encode($json);
                    exit;
                }
                $count = 0;
                $has_count = 0;
                foreach($list as $item){
                    $data = $item;
                    $info = $this->model->where(['name'=>$data['name']])->find();
                    $data['businesses_id'] = $this->businesses_id;
                    if(empty($info)){
                        if($id = $this->model->insert($data,true,true)){
                            admin_log("新增供应商信息，ID：".$id);
                            $count++;
                        }
                    }else{
                        if($this->model->where(['id'=>$info['id']])->update($data)){
                            $id = $info['id'];
                            admin_log("更新供应商信息，ID：".$id);
                            $has_count++;
                        }
                    }
                }
                $json['status'] = $count>0?1:0;
                $json['msg'] = '上传'.($count>0?'成功':'失败').',成功记录 '.$count.' 条,已存在记录 '.$has_count.' 条';
                echo json_encode($json);
                exit;
            }
        }

        echo json_encode($json);
        exit;
    }

    /*
    * 批量删除
    */
    public function betch_del(){
        $json = [
            'status' => 0,
            'msg' => '请选择所要删除的记录'
        ];
        $supplier_ids = input('supplier_ids');
        if(!empty($supplier_ids) && count($supplier_ids)>0){
            $supplierIdArr = explode(',',$supplier_ids);
            if($this->model->where(['id'=>['in',$supplierIdArr]])->delete()){
                $json['status'] = 1;
                $json['msg'] = '删除成功';
                admin_log("删除供应商，ID：$supplier_ids");
            }else{
                $json['msg'] = $this->model->getError();
            }
        }

        echo json_encode($json);
        exit;
    }
}